'''
Created on 14-Jul-2010

@author: dexen
'''

import os
import sys

import dexen

import constants


def enableHouModule():
    '''Set up the environment so that "import hou" works.'''
    # Importing hou will load in Houdini's libraries and initialize Houdini.
    # In turn, Houdini will load any HDK extensions written in C++.  These
    # extensions need to link against Houdini's libraries, so we need to
    # make sure that the symbols from Houdini's libraries are visible to
    # other libraries that Houdini loads.  So, we adjust Python's dlopen
    # flags before importing hou.
    if hasattr(sys, "setdlopenflags"):
        old_dlopen_flags = sys.getdlopenflags()
        import DLFCN
        sys.setdlopenflags(old_dlopen_flags | DLFCN.RTLD_GLOBAL)

    try:
        import hou
    except ImportError:
        # Add $HFS/houdini/python2.5libs to sys.path so Python can find the
        # hou module.
        sys.path.append( os.environ['HFS'] + "/houdini/python%d.%dlibs" % sys.version_info[:2])
        import hou
    finally:
        if hasattr(sys, "setdlopenflags"):
            sys.setdlopenflags(old_dlopen_flags)
            
def render(hou_render_path):
    enableHouModule()
    import hou
    hou.hipFile.load(hou_render_path)
    hou.node("/out/mantra_perspective1").render()
    hou.node("/img/comp1/rop_comp1").render()
    
    prev_path = os.getcwd()
    os.chdir(constants.HOUDINI_BASE_FILE_PATH)
    f = open("overhangschema.jpg", "r")
    image = f.read()
    f.close()
    os.chdir(prev_path)
    return image

def gen_image(ind):
    ind.archive_data("image.jpg", render(constants.HOUDINI_RENDER_PATH))
    
    
class ImagingTask(dexen.Task):
    def __init__(self):
        pass
    
    def __execute__(self, inds=[]):
        for ind in inds:
            gen_image(ind)
        return inds
    
    def __isvalid__(self, ind):
        return ind.phen_daylight != None and ind.phen_energy != None 


    